#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
质量分级系统使用示例
演示如何使用质量系统
"""

from pathlib import Path
import json

from generate_video.pipeline.quality_system import (
    QualityLevel,
    QualityConfig,
    QualityValidator,
    QualityReporter,
    QualityManager,
)


def demo_quality_levels():
    """演示不同质量级别"""
    print("=" * 60)
    print("质量级别演示")
    print("=" * 60)

    for level in QualityLevel:
        config = QualityConfig(level)
        print(f"\n{config}")
        print(f"  描述: {config.config['description']}")
        print(f"  视频: {config.get_video_config()['resolution']} @ {config.get_video_config()['frame_rate']}fps")
        print(f"  音频: {config.get_audio_config()['sample_rate']}Hz")
        print(f"  渲染: {config.get_render_config()['max_workers']} workers")


def demo_quality_config():
    """演示质量配置"""
    print("\n" + "=" * 60)
    print("质量配置演示")
    print("=" * 60)

    # 创建标准质量配置
    config = QualityConfig(QualityLevel.STANDARD)

    print(f"\n原始配置:")
    print(f"  分辨率: {config.get_video_config()['resolution']}")
    print(f"  帧率: {config.get_video_config()['frame_rate']}")

    # 更新配置
    print(f"\n更新配置...")
    config.update_config("video", {"frame_rate": 60, "resolution": (2560, 1440)})

    print(f"  分辨率: {config.get_video_config()['resolution']}")
    print(f"  帧率: {config.get_video_config()['frame_rate']}")


def demo_quality_validation():
    """演示质量验证"""
    print("\n" + "=" * 60)
    print("质量验证演示")
    print("=" * 60)

    validator = QualityValidator()

    # 有效配置
    print("\n有效配置验证:")
    valid_video = {
        "resolution": (1920, 1080),
        "frame_rate": 30,
        "bitrate": "5000k",
    }
    is_valid, errors = validator.validate_video_config(valid_video)
    print(f"  有效: {is_valid}")
    if not is_valid:
        print(f"  错误: {errors}")

    # 无效配置
    print("\n无效配置验证:")
    invalid_video = {
        "resolution": (100, 100),
        "frame_rate": 200,
    }
    is_valid, errors = validator.validate_video_config(invalid_video)
    print(f"  有效: {is_valid}")
    if not is_valid:
        print(f"  错误: {errors}")


def demo_quality_report():
    """演示质量报告"""
    print("\n" + "=" * 60)
    print("质量报告演示")
    print("=" * 60)

    # 生成超高质量报告
    config = QualityConfig(QualityLevel.ULTRA)
    report = QualityReporter.generate_report(config)

    print(f"\n质量级别: {report['quality_level']}")
    print(f"质量名称: {report['quality_name']}")
    print(f"描述: {report['description']}")

    print(f"\n视频配置:")
    video = report['video']
    print(f"  分辨率: {video['resolution']}")
    print(f"  帧率: {video['frame_rate']}fps")
    print(f"  码率: {video['bitrate']}")

    print(f"\n音频配置:")
    audio = report['audio']
    print(f"  采样率: {audio['sample_rate']}Hz")
    print(f"  码率: {audio['bitrate']}")
    print(f"  声道: {audio['channels']}")

    print(f"\n估算统计:")
    stats = report['estimated_stats']
    print(f"  分辨率: {stats['resolution']}")
    print(f"  帧率: {stats['frame_rate']}")
    print(f"  估算大小: {stats['estimated_size_mb']}MB")
    print(f"  估算渲染时间: {stats['estimated_render_time_minutes']}分钟")

    print(f"\n验证结果:")
    validation = report['validation']
    print(f"  有效: {validation['is_valid']}")
    if validation['errors']:
        print(f"  错误: {validation['errors']}")

    # 保存报告
    output_file = Path("examples/output/quality_report.json")
    QualityReporter.save_report(report, output_file)
    print(f"\n报告已保存到: {output_file}")


def demo_quality_manager():
    """演示质量管理器"""
    print("\n" + "=" * 60)
    print("质量管理器演示")
    print("=" * 60)

    manager = QualityManager()

    # 设置质量
    print(f"\n当前质量: {manager.current_quality.value}")
    manager.set_quality(QualityLevel.HIGH)
    print(f"更新后: {manager.current_quality.value}")

    # 获取配置
    print(f"\n视频配置:")
    video_config = manager.get_video_config()
    print(f"  分辨率: {video_config['resolution']}")
    print(f"  帧率: {video_config['frame_rate']}")

    # 自动选择质量
    print(f"\n自动选择质量:")
    quality = manager.auto_select_quality(
        target_duration=30,
        hardware_level="high",
    )
    print(f"  30秒视频 + 高端硬件 -> {quality.value}")

    quality = manager.auto_select_quality(
        target_duration=600,
        hardware_level="low",
    )
    print(f"  10分钟视频 + 低端硬件 -> {quality.value}")


def demo_custom_quality():
    """演示自定义质量"""
    print("\n" + "=" * 60)
    print("自定义质量演示")
    print("=" * 60)

    # 基于标准质量创建自定义配置
    config = QualityConfig(QualityLevel.STANDARD)

    # 自定义视频设置
    config.update_config("video", {
        "resolution": (3840, 2160),  # 4K
        "frame_rate": 60,
        "bitrate": "20000k",
    })

    # 自定义渲染设置
    config.update_config("render", {
        "max_workers": 12,
        "timeout": 1800,
    })

    print(f"\n自定义配置:")
    print(f"  视频: {config.get_video_config()['resolution']} @ {config.get_video_config()['frame_rate']}fps")
    print(f"  码率: {config.get_video_config()['bitrate']}")
    print(f"  渲染器: {config.get_render_config()['max_workers']} workers")

    # 生成报告
    report = QualityReporter.generate_report(config)
    print(f"\n验证状态: {report['validation']['is_valid']}")


if __name__ == "__main__":
    # 创建输出目录
    Path("examples/output").mkdir(parents=True, exist_ok=True)

    # 运行所有演示
    demo_quality_levels()
    demo_quality_config()
    demo_quality_validation()
    demo_quality_report()
    demo_quality_manager()
    demo_custom_quality()

    print("\n" + "=" * 60)
    print("演示完成!")
    print("=" * 60)
